package com.yixin.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yixin.entity.Emp;
import com.yixin.entity.LoginInfo;
import com.yixin.entity.PageResult;
import com.yixin.mapper.EmpMapper;
import com.yixin.entity.EmpQueryParam;
import com.yixin.service.EmpService;
import com.yixin.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Override
    public void add(Emp emp) {
        if (emp.getGender() == null) {
            emp.setGender(1);
        }
        emp.setIsDel(0);
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.add(emp);
    }

    @Override
    public void update(Emp emp) {
        if (emp.getGender() == null) {
            emp.setGender(1);
        }
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        empMapper.deleteById(ids);
    }

    @Override
    public PageResult<Emp> findPage(EmpQueryParam  param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Emp> list = empMapper.findPage(param);
        Page<Emp> empPage = (Page<Emp>) list;
        return new PageResult<>(empPage.getTotal(), empPage.getResult());
    }

    @Override
    public LoginInfo login(Emp emp) {
        Emp e = empMapper.selectByPhoneAndPwd(emp);
        if (e != null) {
            Map<String, Object> Claims = new HashMap<>();
            Claims.put("id", e.getId());
            Claims.put("phone", e.getPhone());
            Claims.put("name", e.getName());
            String jwt = JWTUtils.generateJWT(Claims);
            return new LoginInfo(e.getId(), e.getName(), e.getPhone(), jwt);
        }
        return null;
    }
}
